/**
 * Created by wxb on 2016/10/12.
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.theme.components')
    .controller('ImageUploadCtrl', ImageUploadCtrl);

  /** @ngInject */
  function ImageUploadCtrl($scope, $q, $qupload, $log, qiniuToken, rfc4122, $uibModal) {
    var token;
    var imgBaseUrl;
    var innerKey;

    if ($scope.ARmagicLibrary) {
      qiniuToken.cooperationToken().then(function (data) {
        token = data.data.token;
      });
      qiniuToken.productBaseUrl().then(function (data) {
        imgBaseUrl = data;
      });
      innerKey = 'hm/ar/image/'
    }
    else {
      qiniuToken.imgToken().then(function (data) {
        token = data.data.token;
      });
      qiniuToken.imgBaseUrl().then(function (data) {
        imgBaseUrl = data;
      });
    }


    $scope.imgSelectFiles = [];
    $scope.imgUploading = false;

    var start = function (index) {
      $scope.imgSelectFiles[index].progress = {
        p: 0
      };
      $scope.imgSelectFiles[index].upload = $qupload.upload({
        key: ($scope.key || innerKey) + rfc4122.v4() + '.' + $scope.imgSelectFiles[index].file.name.split(".").pop(),
        file: $scope.imgSelectFiles[index].file,
        token: token
      });
      $scope.imgSelectFiles[index].upload.then(function (response) {
        $log.info(response);
        $scope.imgUrl = imgBaseUrl + response.key;
        if ($scope.title) {$scope.title.imgUrl = imgBaseUrl + response.key;}
        $scope.formData.currImg = response.key;
      }, function (response) {
        $log.info(response);
      }, function (evt) {
        $scope.imgSelectFiles[index].progress.p = Math.floor(100 * evt.loaded / evt.totalSize);
        $scope.imgProgressbarValue = $scope.imgSelectFiles[index].progress.p;
        if (evt) {
          $scope.imgUploading = true;
        }
        // if ($scope.imgSelectFiles[index].progress.p === 100) {
        //   $scope.uploading = false;
        // }

      });
    };

    $scope.abort = function (index) {
      $scope.imgSelectFiles[index].upload.abort();
      $scope.imgSelectFiles.splice(index, 1);
    };

    $scope.onImgSelect = function ($files) {
      if ($scope.needCrop) {
        var cropSrcFile = $files.slice(-1)[0];
        var cropSrcFileName = cropSrcFile.name;
        getBase64(cropSrcFile).then(function (base64Data) {
          var modalInstance = $uibModal.open({
            backdrop  : 'static',
            keyboard  : false,
            animation: true,
            templateUrl: 'app/theme/components/imageUpload/modal/imageCrop.html',
            controller: 'ImageCropModalCtrl',
            resolve: {
              cropSrc: function () {
                return base64Data;
              },
              cropWidth: function () {
                return $scope.cropWidth;
              },
              cropHeight: function () {
                return $scope.cropHeight;
              }
            }
          });
          modalInstance.result.then(function (modalItem) {
            var cropFile = dataURLtoFile(modalItem, cropSrcFileName);
            var files = [];
            files.push(cropFile);
            var offsetx = $scope.imgSelectFiles.length;
            for (var i = 0; i < files.length; i++) {
              $scope.imgSelectFiles[i + offsetx] = {
                file: files[i]
              };
              start(i + offsetx);
            }
          })
        });
      }
      else {
        var offsetx = $scope.imgSelectFiles.length;
        for (var i = 0; i < $files.length; i++) {
          $scope.imgSelectFiles[i + offsetx] = {
            file: $files[i]
          };
          start(i + offsetx);
        }
      }
    };


    function getBase64(file) {
      var deferred = $q.defer();
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function () {
        deferred.resolve(reader.result);
      };
      reader.onerror = function (error) {
        console.log('Error: ', error);
        deferred.resolve(undefined);
      };
      return deferred.promise;
    }

    function dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type:mime});
    }


  }
})();

